import heapq
import json

from querier.esquerier import ElasticSearchQuerier
import utils.utils as uc
import math
import querier.weibo.utils as utils
import operator
import re

MINIMUM_SHOULD_MATCH = '5<85% 10<9'
MAX_BRANDS = 40
MAX_CHARACTER = 50
MAX_KEYWORDS = 10
MAX_CATEGORY = 16
CATEGORY_CUTOFF = 0.9


class WeiboKOLMatchMiniQuerier(ElasticSearchQuerier):
    def __init__(self, es, index, doc_type, nlp_service):
        super(WeiboKOLMatchMiniQuerier, self).__init__(es, index, doc_type)
        self.nlp_service = nlp_service

    def _build_query(self, args):
        """
        从args创建查询
        :param args:
        :return:
        """

        term = args.get('term', '')
        term = term if term else ''
        filters = args.get('filters', {})
        filters = filters if filters else {}
        order = args.get('order_by', utils.ORDER_OVERALL)
        order = order if order else utils.ORDER_OVERALL
        from_ = args.get('from', 0)
        from_ = from_ if from_ else 0
        size_ = args.get('size', 10)
        size_ = size_ if size_ else 10
        highlight = args.get('highlight', False)
        highlight = highlight if highlight in (True, False) else False

        # 处理查询文本
        term2, keywords, ex_keywords, weights = utils.process_query_term(term, self.nlp_service)
        query = self._gen_query(' '.join(keywords), term, filters, order, from_, size_, highlight)
        return query, {}, {'keywords': keywords, 'order': order}

    def _build_result(self, es_result, param):
        keywords = param['keywords']
        order = param['order']

        total = es_result['hits']['total']
        max_score = es_result['hits']['max_score']

        weibo = []

        for hit in es_result['hits']['hits']:
            weibo.append(extract_result(hit, max_score, order, keywords))
        return {
            'total': total,
            'keywords': keywords,
            'weibo': weibo,
            'ex_keywords': param.get('ex_keywords', []),
            'ex_category': param.get('ex_category', [])
        }

    def _gen_query(self, query_keywords, term, filters, order, from_, size_, highlight):
        must_clause = []
        query = {}

        filter_clause = []
        if filters:
            filter_clause = self._add_filter_clause(filter_clause, filters, 'keywords')
            filter_clause = self._add_filter_range_clause(filter_clause, filters, 'avg_likes')
            filter_clause = self._add_filter_range_clause(filter_clause, filters, 'avg_retweets')
            filter_clause = self._add_filter_range_clause(filter_clause, filters, 'avg_comments')
            filter_clause = self._add_filter_range_clause(filter_clause, filters, 'timestamp')
            filter_clause = self._add_filter_range_clause(filter_clause, filters, 'score')
            filter_clause = self._add_filter_match(filter_clause, filters, 'user_id')
            filter_clause = self._add_filter_match(filter_clause, filters, 'nick_name')
            filter_clause = self._add_filter_match(filter_clause, filters, 'description')
            filter_clause = self._add_filter_clause(filter_clause, filters, 'user_type')

            filter_clause = self._add_filter_clause_minus(filter_clause, filters, 'verified_type', 'should')

            if filters.get('category'):
                filters['category'] = [uc.category_smzdm_2_encode(c) for c in filters['category']]
                filter_clause = self._add_filter_clause(filter_clause, filters, 'category', 'should')

            if filters.get('category_media'):
                filters['category_media'] = [uc.category_media_2_encode(c) for c in filters['category_media']]
                # filters['category_media_weight'] = [CATEGORY_CUTOFF]
                filter_clause = self._add_filter_clause(filter_clause, filters, 'category_media', 'should')
                # filter_clause = self._add_filter_range_clause(filter_clause, filters, 'category_media_weight')

        query = {"query": {"bool": {}}}
        if filter_clause:
            query['query']['bool']['filter'] = filter_clause

        if query_keywords.strip() or term.strip():
            query['query']['bool']['must'] = {
                'bool': {
                    'should': [
                        {
                            'match': {
                                'user_id': {
                                    'analyzer': 'whitespace',
                                    'query': term.strip()[0: MAX_CHARACTER],
                                    'boost': 4,
                                }
                            }
                        },
                        {
                            'match_phrase': {
                                'nick_name': {
                                    'query': term.strip()[0:MAX_CHARACTER],
                                    'boost': 20,
                                }
                            }
                        },
                        {
                            'match_phrase': {
                                'description': {
                                    'query': term.strip()[0:MAX_CHARACTER],
                                    'boost': 1,
                                }
                            }
                        }
                    ]
                }
            }

        query['sort'] = []
        if order == utils.ORDER_INFLUENCE:
            query['sort'] = [
                {'score': 'desc'},
                {'_score': 'desc'}
            ]
        elif order == utils.ORDER_RELATIVE:
            query['sort'] = [
                {
                    '_script': {
                        "type": "number",
                        "script": {
                            "lang": "painless",
                            "inline": "Math.log(_score + 1.1) * Math.log(doc.avg_engagement.value + 100)"
                        },
                        "order": "desc"
                    },

                },
                {'avg_engagement': 'desc'}
            ]
        elif order == utils.ORDER_TIMESTAMP:
            query['sort'] = [
                {'timestamp': 'desc'},
                {'score': 'desc'}
            ]
        elif order == 'avg_likes':
            query['sort'] = [
                {'avg_likes': 'desc'},
                {'_score': 'desc'}
            ]
        elif order == 'avg_retweets':
            query['sort'] = [
                {'avg_retweets': "desc"},
                {'_score': 'desc'}
            ]
        elif order == 'avg_comments':
            query['sort'] = [
                {'avg_comments': 'desc'},
                {'_score': 'desc'}
            ]
        else:
            query['sort'] = [
                {'_score': 'desc'},
                {'score': 'desc'}
            ]

        # if filters.get('category'):
        #     query['sort'] = [{'category_weight': 'desc'}] + query['sort']

        if highlight:
            query['highlight'] = {
                "pre_tags": ["<span class='keyword'>"],
                "post_tags": ["</span>"],
                "fields": {"nick_name": {}, "description": {}}
            }

        query['track_scores'] = True
        query['from'] = from_
        query['size'] = size_

        return query

    @staticmethod
    def _add_filter_match(must_clause, filters, key, cond='must'):
        if key in filters:
            if filters[key]:
                clause = []
                must_clause.append({
                    'bool': {cond: clause}
                })
                values = filters[key]
                if isinstance(values, str):
                    values = values.split(' ')
                for fk in values:
                    clause.append({'match': {key: {'query': fk, 'minimum_should_match': MINIMUM_SHOULD_MATCH}}})
        return must_clause

    @staticmethod
    def _add_filter_clause(filter_clause, filters, key, cond='must'):
        if key in filters:
            if filters[key]:
                clause = []
                filter_clause.append({
                    'bool': {
                        cond: clause
                    }
                })
                for fk in filters[key]:
                    clause.append({'term': {key: fk}})
        return filter_clause

    @staticmethod
    def _add_filter_clause_minus(filter_clause, filters, key, cond='must'):
        if key in filters:
            if filters[key]:
                clause = []
                filter_clause.append({
                    'bool': {
                        cond: clause
                    }
                })
                for fk in filters[key]:
                    if fk > 0:
                        clause.append({'term': {key: fk}})
                    else:
                        clause.append({'range': {key: {"lte": fk, 'gte': fk}}})
        return filter_clause

    @staticmethod
    def _add_filter_range_clause(filter_clause, filters, key):
        if key in filters:
            if filters[key]:
                clause = []
                filter_clause.append({
                    'bool': {
                        'must': clause
                    }
                })
                fk = filters[key]
                if not isinstance(fk, list) or len(fk) < 1:
                    pass
                else:
                    min_fk = fk[0]
                    if len(fk) >= 2:
                        max_fk = fk[1]
                    else:
                        max_fk = None
                    if min_fk is not None and min_fk != 'null':
                        clause.append({'range': {key: {"gte": min_fk}}})
                    if max_fk is not None and max_fk != 'null':
                        clause.append({'range': {key: {"lte": max_fk}}})
        return filter_clause


def extract_result(hit, max_score, order, in_keywords=[]):
    source_ = hit['_source']
    kol_influence_score = source_['score']
    score_ = hit['_score']
    res = utils.extract_user_from_source(source_)

    res['score'] = kol_influence_score
    res['relative'] = 1 if max_score <= 0 else score_ / max_score

    highlight = hit.get('highlight')
    if highlight:
        h_user_name = highlight.get('nick_name')
        if h_user_name:
            res['user_name'] = h_user_name[0]
        h_user_info = highlight.get('description')
        if h_user_info:
            res['user_info'] = h_user_info[0]

    return res
